package com.yifushidai.utils;

import com.yifushidai.config.ShisuIoHandler;
import com.yifushidai.entity.ResultLock;
import org.apache.commons.lang.StringUtils;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ShisuMinaPushUtils {
    private static Logger logger = LoggerFactory.getLogger(ShisuMinaPushUtils.class);
    public static ConcurrentHashMap<String, ResultLock> lockMap = new ConcurrentHashMap<String, ResultLock>();//线程安全  服务端推送至硬件端用

    public static <T> Object push(String mac, T req) throws InterruptedException {
        if(StringUtils.isBlank(mac) || !mac.matches("^\\w{24}$")) return null;
        mac = mac.toUpperCase();//可能是UniqueMac或PowerMac，硬件端传过来的是16进制大写字符串，这里转大写与之匹配

        for (Map.Entry<String, IoSession> ioSessionMap : ShisuIoHandler.sessionsConcurrentHashMap.entrySet()) {
            if (ioSessionMap.getKey().equalsIgnoreCase(mac)) {
                IoSession ioSession = ioSessionMap.getValue();
                ioSession.write(req);//mina主动push

                String uniqueMac = (String) ioSession.getAttribute("UniqueMac");
                String powerMac = (String) ioSession.getAttribute("PowerMac");
                String remoteAddressAndSocket = (String) ioSession.getAttribute("remoteAddressAndSocket");
                logger.info(">>> 硬件端：{}({}_{}) 参数：{}", remoteAddressAndSocket, uniqueMac, powerMac, req);

                ResultLock resultLock = new ResultLock(mac);
                lockMap.put(mac, resultLock);//此对象放到一个map
                try {
                    synchronized (resultLock) {
                        resultLock.wait(5000);
                    }
                } finally {
                    lockMap.remove(mac);
                }

                return resultLock.getMessage();//取到结果
            }
        }
        return null;
    }
}
